package ljl.alg.jianzhioffer.round2;

public class _47_gift_max_value {
    
    public int maxValue2(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int max = 0;
                if (i > 0) max = Math.max(max, grid[i - 1][j]);
                if (j > 0) max = Math.max(grid[i][j - 1], max);
                grid[i][j] += max;
            }
        }
        return grid[m - 1][n - 1];
    }
    
    /**
     * 稍快点
     * */
    public int maxValue(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for (int i = 1; i < m; i++) {
            grid[i][0] += grid[i - 1][0];
        }
        for (int i = 1; i < n; i++) {
            grid[0][i] += grid[0][i - 1];
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]);
            }
        }
        return grid[m - 1][n - 1];
    }
    
}
